﻿/* $ 扩展 */
(function ($) {

    /* 设置标签的值，同时触发 change 事件 */
    $.fn.setValue = function (val) {
        this.val(val);
        this.change();
    }

    /* 根据值设置 select 标签的选中项，同时触发 change 事件 */
    $.fn.setSelectedValue = function (val) {
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            for (var i = 0; i < selectElement.options.length; i++) {
                var op = selectElement.options[i];
                if (op.value == val) {
                    op.selected = true;
                    $(selectElement).change();
                    break;
                }
            }
        }
    };
    $.fn.getSelectedValue = function () {
        var ret = "";
        var c = "";
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            var idx = selectElement.selectedIndex;
            ret += c + selectElement[idx].value;
            c = ";";
        }

        return ret;
    };
    $.fn.getSelectedText = function () {
        var ret = "";
        var c = "";
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            var idx = selectElement.selectedIndex;
            ret += c + selectElement[idx].text;
            c = ";";
        }

        return ret;
    };

    /* 设置 radio、checkbox 状态为选中 */
    $.fn.checked = function () {
        for (var j = 0; j < this.length; j++) {
            var ele = this[j];
            var old = ele.checked;
            ele.checked = true;
            if (old != ele.checked)
                $(ele).change();
        }
    }
    /* 设置 radio、checkbox 状态为未选中 */
    $.fn.unchecked = function () {
        for (var j = 0; j < this.length; j++) {
            var ele = this[j];
            var old = ele.checked;
            ele.checked = false;
            if (old != ele.checked)
                $(ele).change();
        }
    }
    /* 设置 radio、checkbox 状态。如果传入的 value 与控件的 value 相等，则设置为选中，否则不选中 */
    $.fn.setChecked = function (value) {
        var inputValues = [];

        if (value instanceof Array) {
            inputValues = value;
        }
        else {
            inputValues.push(value);
        }

        var values = [];

        for (var i = 0; i < inputValues.length; i++) {
            var value = inputValues[i];
            if (value === true)
                values.push("true");
            else if (value === false)
                values.push("false");
            else if (value !== undefined && value !== null) {
                values.push(value);
            }
        }

        for (var i = 0; i < this.length; i++) {
            var ele = this[i];
            var checked = false;
            for (var j = 0; j < values.length; j++) {
                var value = values[j];
                if (ele.value == value) {
                    checked = true;
                    break;
                }
            }

            var old = ele.checked;

            if (checked) {
                ele.checked = true;
            }
            else {
                ele.checked = false;
            }

            if (old != ele.checked)
                $(ele).change();
        }
    }
    /* 获取被选中的 radio、checkbox 值 */
    $.fn.getCheckedValue = function () {
        for (var j = 0; j < this.length; j++) {
            var ele = this[j];
            if (ele.checked == true) {
                return ele.value;
            }
        }
        return null;
    }

    $.fn.formValid = function () {
        return true;//未做前端校验
        return $(this).valid({
            errorPlacement: function (error, element) {
                element.parents('.formValue').addClass('has-error');
                element.parents('.has-error').find('i.error').remove();
                element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
                $("[data-toggle='tooltip']").tooltip();
                if (element.parents('.input-group').hasClass('input-group')) {
                    element.parents('.has-error').find('i.error').css('right', '33px')
                }
            },
            success: function (element) {
                element.parents('.has-error').find('i.error').remove();
                element.parent().removeClass('has-error');
            }
        });
    }

    $.fn.getFormData = function () {
        var $form = $(this);
        var model = {};
        $form.find('input,select,textarea').each(function (r) {
            var $this = $(this);
            var name = $this.attr('name');

            if (!name)
                return;

            var type = $this.attr('type');
            if ($this.attr("disabled") == "disabled")
                return;

            switch (type) {
                case "checkbox":
                    var checkboxValues;
                    if (name in model) {
                        checkboxValues = model[name];
                    }
                    else {
                        checkboxValues = [];
                        model[name] = checkboxValues;
                    }

                    if (this.checked) {
                        checkboxValues.push($this.val());
                    }
                    break;
                case "radio":
                    if (model[name] === undefined)
                        model[name] = null;
                    if (this.checked == true)
                        model[name] = this.value;
                    break;
                case "button":
                    break;
                default:
                    var value = $this.val();
                    model[name] = value;
                    break;
            }
        });
        if ($('[name=__RequestVerificationToken]').length > 0) {
            model["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        return model;
    };
    $.fn.setFormData = function (data) {
        var $form = $(this);
        $form.find('input,select,textarea').each(function (r) {
            var $ele = $(this);
            var name = $ele.attr('name');

            if (!name)
                return;

            var type = $ele.attr('type');

            var value = null;
            if (name in data)
                value = data[name];
            else
                return;//如果模型中不存在相应的name属性，则不管

            switch (type) {
                case "checkbox":
                    var values = value || []; //对于checkbox，value是一个数组

                    for (var i = 0; i < $ele.length; i++) {
                        var checkbox = $ele[i];
                        var checkboxValue = checkbox.value;
                        var checked = false;
                        for (var j = 0; j < values.length; j++) {
                            if (checkboxValue == values[j]) {
                                checked = true;
                                break;
                            }
                        }
                        checkbox.checked = checked;
                    }
                    break;
                case "radio":
                    $ele.setChecked(value);
                    break;
                case "select":
                    $ele.val(value).trigger("change");
                    break;
                case "button":
                    break;
                default:
                    $ele.val(value);
                    break;
            }
        });
    };

    $.fn.bindSelect = function (options) {
        var defaults = {
            value: "Id",
            text: "Name",
            change: null,
            items: [],
            placeholder: "-请选择-"
        };
        var options = $.extend(defaults, options);
        var $element = $(this);

        if (options.placeholder !== null && options.placeholder !== undefined)
            $element.append($("<option></option>").val("").html(options.placeholder));

        items = options.items;
        $.each(items, function (i) {
            $element.append($("<option></option>").val(items[i][options.value]).html(items[i][options.text]));
        });

        if (options.change)
            $element.change(options.change);

        return;
    }

    $.fn.disable = function () {
        var $element = $(this);
        $element.attr("disabled", "disabled");
    }
    $.fn.enable = function () {
        var $element = $(this);
        $element.removeAttr("disabled");
    }


    $.loading = function (bool, text) {
        var $loadingpage = top.$("#loadingPage");
        var $loadingtext = $loadingpage.find('.loading-content');
        if (bool) {
            $loadingpage.show();
        } else {
            if ($loadingtext.attr('istableloading') == undefined) {
                $loadingpage.hide();
            }
        }
        if (!!text) {
            $loadingtext.html(text);
        } else {
            $loadingtext.html("数据加载中，请稍后…");
        }
        $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
        $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
    }
})($);
